package net.skyaims.sqlmgr.service;

import net.skyaims.sqlmgr.config.DispatchConfiguration;
import net.skyaims.sqlmgr.dao.HostDao;
import net.skyaims.sqlmgr.dao.IdcDao;
import net.skyaims.sqlmgr.dao.IdcServerDao;
import net.skyaims.sqlmgr.dao.NodeDao;
import net.skyaims.sqlmgr.resource.IdcResource;
import net.skyaims.sqlmgr.resource.IdcServerResource;

import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.db.Database;
import com.yammer.dropwizard.db.DatabaseFactory;

public class DispatchService extends Service<DispatchConfiguration> {

	public static void main(String[] args) {
		try {
			String[] defaultArgs = new String[] { "server", "conf.yml" };
			defaultArgs = (args == null || args.length == 0) ? defaultArgs : args;
			new DispatchService().run(defaultArgs);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	@Override
	protected void initialize(DispatchConfiguration configuration, Environment environment) throws Exception {

		final DatabaseFactory factory = new DatabaseFactory(environment);

		final Database altDatabase = factory.build(configuration.getAllotDatabase(), "dbconfig");
		final IdcDao idcDao = altDatabase.onDemand(IdcDao.class);
		final IdcServerDao idcServerDao = altDatabase.onDemand(IdcServerDao.class);

		final Database lrcDatabase = factory.build(configuration.getLiveRoomCenterDatabase(), "dbconfig");
		final NodeDao nodeDao = lrcDatabase.onDemand(NodeDao.class);
		final HostDao hostDao = lrcDatabase.onDemand(HostDao.class);

		environment.addResource(new IdcResource(idcDao, nodeDao));
		environment.addResource(new IdcServerResource(idcServerDao, hostDao));

	}

}
